<?php

namespace addons\shopro\job;

use addons\shopro\service\Wallet as WalletService;
use app\admin\model\RechargeCorrectLog;
use app\admin\model\shopro\Bonus;
use app\admin\model\shopro\BonusLog;
use app\admin\model\shopro\Config as ShoproConfig;
use app\admin\model\shopro\Pclog;
use app\admin\model\shopro\Performance;
use app\admin\model\shopro\user\User;
use think\queue\Job;
use think\Db;
use think\exception\HttpResponseException;
use addons\shopro\service\commission\Agent as AgentService;

/**
 * 分红接力赛
 */
class Dividend extends BaseJob
{

    /**
     * 分红接力赛
     */
    public function index(Job $job, $payload)
    {
        try {
            Db::transaction(function ()  {
                $this->dividend();
            });
            $job->delete();
        } catch (HttpResponseException $e) {
            $data = $e->getResponse()->getData();
            $message = $data ? ($data['msg'] ?? '') : $e->getMessage();
            $job->delete();
            format_log_error($e, 'RechargeCorrect.HttpResponseException', $message);
        } catch (\Exception $e) {
            format_log_error($e, 'RechargeCorrect');
        }
    }

    public function dividend()
    {
        $configs = ShoproConfig::getConfigs('shop.bonus.bonus_pool', false);
        $user=User::alias("user")
            ->join("shopro_commission_agent agent","user.id=agent.user_id")
            ->where(["agent.level"=>$configs["level"],"is_dividend"=>1])
            ->where("dividend_level_time is not null")
            ->order("dividend_level_time","asc")
            ->select();//查找等级满足分红接力赛用户
        if(!empty($user)){
            foreach($user as $user){
                $parent_user_id=\app\common\model\User::where("parent_user_id",$user["id"])->column("id");
                if(!empty($parent_user_id)){
                    $now_time=strtotime(date("Y-m-d",time()));
                    $user_bonus=(new \app\admin\model\shopro\user\Bonus)->where(["user_id"=>$user["id"]])->order("createtime","desc")->find();
                    if(!empty($user_bonus)){
                        //之前已经分红--时间从上次分红时间推算
                        $time=strtotime(date("Y-m-d",strtotime($user_bonus["createtime"])));
                    }else{
                        $time=strtotime(date("Y-m-d",strtotime("-6 month")));
                        $user["dividend_level_time"]=strtotime(date("Y-m-d",$user["dividend_level_time"]));
                        if($user["dividend_level_time"]<$time){
                            //如果已经超过半年时间
                            $time=$user["dividend_level_time"];
                        }
                    }
                    $where["createtime"]=["between",[$time,$now_time]];
                    $where_dividend["is_dividend"]=["=",1];
//                    $where_dividend["is_self"]=["=",0];
                    $order_ids=Performance::field("GROUP_CONCAT(DISTINCT order_id) money")
                        ->where($where)
                        ->where($where_dividend)
                        ->buildSql();
                    $self_performance_data = Performance::field("sum(money) money")
                        ->where(["user_id"=>$user["id"]])
                        ->where($where)
                        ->where($where_dividend)
                        ->union([$order_ids], true)
                        ->select();//所有
                    $self_performance=$self_performance_data[0]["money"]??0;
                    if(!empty($user_bonus)){
                        //之前已经分红--加上上次结余业绩
                        $self_performance=bcadd(bcadd($self_performance,$user_bonus["big_money"]),$user_bonus["small_money"]);
                    }
                    if($self_performance>=1000000){
                        $ids=$self_performance_data[1]["money"]??0;
                        $list = Performance::whereIn("user_id",$parent_user_id)
                            ->field("sum(money) money,user_id")
                            ->where($where)
                            ->whereIn("order_id",$ids)
                            ->group("user_id")
                            ->select();
                        if(!empty($list)){
                            $big_market=0;
                            $market=0;
                            foreach ($list as $v){
                                $big_market = max($big_market , $v['money']);
                                $market+=$v["money"];
                            }
                            $small_market=bcsub($market,$big_market,2);
                            $big_market=bcadd($user_bonus["big_money"]??0,$big_market,2);//加上上次结余大市场业绩
                            $small_market=bcadd($user_bonus["small_money"]??0,$small_market,2);//加上上次结余小市场业绩
                            if($small_market>=200000){
                                //小市场大于20w
                                $bonus=Bonus::find();//奖金池
                                if($bonus && $bonus["money"]>0){
                                    $bonus_money=bcmul($bonus["money"],($configs["divvy_rate"]/100),2);//分红金额
                                    //变更用户余额
                                    if($small_market>=1000000){
                                        //小市场大于等于100w
                                        $small_money_money=0;
                                        $small_market_cut=1000000;
                                        $small_money=bcsub($small_market,1000000,2);//小市场结余金额
                                    }else{
                                        $small_money=0;
                                        $small_money_money=bcsub(1000000,$small_market,2);//小市场扣除之后还剩余多少
                                        $small_market_cut=$small_market;
                                    }
                                    if($small_money_money>0){
                                        /*$big_market_cut=bcsub($big_market,$small_money_money,2);//大市场剩余
                                        $big_market_cut=bcsub($big_market,$big_market_cut,2);//大市场扣除*/
                                        $big_market_cut=$small_money_money;
                                        $big_money=bcsub($big_market,$big_market_cut,2);//大市场结余金额
                                    }else{
                                        $big_market_cut=0;
                                        $big_money=$big_market;
                                    }
                                    if($bonus_money>0){
                                        $ext=[
                                            "big_money"=>$big_money,//大市场结余金额，
                                            "small_money"=>$small_money,//小市场结余金额，
                                            "big_market"=>$big_market_cut,//大市场扣除金额
                                            "small_market"=>$small_market_cut,//小市场扣除金额
                                            "bonus"=>$bonus_money,//分红金额
                                            "bonus_money"=>$bonus["money"],//奖金池金额
                                            "divvy_rate"=>$configs["divvy_rate"],//分红比例
                                        ];
                                        WalletService::change($user["id"], "money", $bonus_money, 'money_dividend', [], "分红接力赛收益");
                                        $bonus->setDec("money",$bonus_money);
                                        $logModel= new BonusLog();
                                        $logModel->save([
                                            "money"=>-$bonus_money,
                                            "order_id"=>0,
                                            "order_pv"=>$bonus["money"],
                                            "user_id"=>$user["id"],
                                            "createtime"=>time(),
                                            "momo"=>"分红接力赛收益发放",
                                            "order_no"=>0,
                                            "type"=>1,
                                            "ratio"=>$configs["divvy_rate"],
                                            "order_details"=>json_encode($ext),
                                        ]);
                                        //生成分红记录
                                        $bonus=(new \app\admin\model\shopro\user\Bonus)->create([
                                            "user_id"=>$user["id"],
                                            "big_money"=>$big_money,//大市场结余金额，
                                            "small_money"=>$small_money,//小市场结余金额，
                                            "big_market"=>$big_market_cut,//大市场扣除金额
                                            "small_market"=>$small_market_cut,//小市场扣除金额
                                            "bonus"=>$bonus_money,//分红金额
                                            "ext"=>json_encode($ext),//分红金额
                                        ]);
                                        //记录平台支出
                                        Pclog::create([
                                            "order_id"=>$bonus["id"],
                                            "money"=>-$bonus_money,
                                            "type"=>3,
                                            "pv_price"=>$bonus["bonus"],
                                            "ext"=>$ext,
                                            "user_id"=>$user["id"],
                                            "createtime"=>time(),
                                        ]);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
